package com.blankii.androidlibrary.views

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.blankii.androidlibrary.R

/**
 * author: blankii
 * created on: 2024/4/26 13:59
 * description:
 */
class DividerItemDecoration(
    context: Context, color: Int = R.color.black, dividerHeight: Int = R.dimen.divider_height
) : RecyclerView.ItemDecoration() {
    private var dividerHeight: Int
    private var dividerPaint: Paint = Paint()

    init {
        dividerPaint.setColor(context.resources.getColor(color, null))
        this.dividerHeight = context.resources.getDimensionPixelSize(dividerHeight)
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        outRect.bottom = dividerHeight
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val childCount = parent.childCount
        val left = parent.getPaddingLeft()
        val right = parent.width - parent.getPaddingRight()
        for (i in 0 until childCount) {
            val view = parent.getChildAt(i)
            val top = view.bottom.toFloat()
            val bottom = (view.bottom + dividerHeight).toFloat()
            c.drawRect(left.toFloat(), top, right.toFloat(), bottom, dividerPaint)
        }
    }
}